//钱包合约的ABI
const eCNYABI = [
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "spender",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "approve",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address[]",
				"name": "recipients",
				"type": "address[]"
			},
			{
				"internalType": "uint256[]",
				"name": "amounts",
				"type": "uint256[]"
			}
		],
		"name": "batchTransferETH",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address[]",
				"name": "recipients",
				"type": "address[]"
			},
			{
				"internalType": "uint256[]",
				"name": "amounts",
				"type": "uint256[]"
			}
		],
		"name": "batchTransferTokens",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "buyTokensWithETH",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "payable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "_amount",
				"type": "uint256"
			}
		],
		"stateMutability": "nonpayable",
		"type": "constructor"
	},
	{
		"inputs": [],
		"name": "ECDSAInvalidSignature",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "length",
				"type": "uint256"
			}
		],
		"name": "ECDSAInvalidSignatureLength",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "bytes32",
				"name": "s",
				"type": "bytes32"
			}
		],
		"name": "ECDSAInvalidSignatureS",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "spender",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "allowance",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "needed",
				"type": "uint256"
			}
		],
		"name": "ERC20InsufficientAllowance",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "sender",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "balance",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "needed",
				"type": "uint256"
			}
		],
		"name": "ERC20InsufficientBalance",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "approver",
				"type": "address"
			}
		],
		"name": "ERC20InvalidApprover",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "receiver",
				"type": "address"
			}
		],
		"name": "ERC20InvalidReceiver",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "sender",
				"type": "address"
			}
		],
		"name": "ERC20InvalidSender",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "spender",
				"type": "address"
			}
		],
		"name": "ERC20InvalidSpender",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "deadline",
				"type": "uint256"
			}
		],
		"name": "ERC2612ExpiredSignature",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "signer",
				"type": "address"
			},
			{
				"internalType": "address",
				"name": "owner",
				"type": "address"
			}
		],
		"name": "ERC2612InvalidSigner",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "account",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "currentNonce",
				"type": "uint256"
			}
		],
		"name": "InvalidAccountNonce",
		"type": "error"
	},
	{
		"inputs": [],
		"name": "InvalidShortString",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "owner",
				"type": "address"
			}
		],
		"name": "OwnableInvalidOwner",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "account",
				"type": "address"
			}
		],
		"name": "OwnableUnauthorizedAccount",
		"type": "error"
	},
	{
		"inputs": [
			{
				"internalType": "string",
				"name": "str",
				"type": "string"
			}
		],
		"name": "StringTooLong",
		"type": "error"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "owner",
				"type": "address"
			},
			{
				"indexed": true,
				"internalType": "address",
				"name": "spender",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "Approval",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [],
		"name": "EIP712DomainChanged",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "from",
				"type": "address"
			},
			{
				"indexed": true,
				"internalType": "address",
				"name": "to",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			}
		],
		"name": "ETHTransferred",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "previousOwner",
				"type": "address"
			},
			{
				"indexed": true,
				"internalType": "address",
				"name": "newOwner",
				"type": "address"
			}
		],
		"name": "OwnershipTransferred",
		"type": "event"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "owner",
				"type": "address"
			},
			{
				"internalType": "address",
				"name": "spender",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "deadline",
				"type": "uint256"
			},
			{
				"internalType": "uint8",
				"name": "v",
				"type": "uint8"
			},
			{
				"internalType": "bytes32",
				"name": "r",
				"type": "bytes32"
			},
			{
				"internalType": "bytes32",
				"name": "s",
				"type": "bytes32"
			}
		],
		"name": "permit",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "renounceOwnership",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "tokenAmount",
				"type": "uint256"
			}
		],
		"name": "sellTokensForETH",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "buyer",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			}
		],
		"name": "TokensPurchased",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "seller",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			}
		],
		"name": "TokensSold",
		"type": "event"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "from",
				"type": "address"
			},
			{
				"indexed": true,
				"internalType": "address",
				"name": "to",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "amount",
				"type": "uint256"
			}
		],
		"name": "TokensTransferred",
		"type": "event"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "to",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "transfer",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"anonymous": false,
		"inputs": [
			{
				"indexed": true,
				"internalType": "address",
				"name": "from",
				"type": "address"
			},
			{
				"indexed": true,
				"internalType": "address",
				"name": "to",
				"type": "address"
			},
			{
				"indexed": false,
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "Transfer",
		"type": "event"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "from",
				"type": "address"
			},
			{
				"internalType": "address",
				"name": "to",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "value",
				"type": "uint256"
			}
		],
		"name": "transferFrom",
		"outputs": [
			{
				"internalType": "bool",
				"name": "",
				"type": "bool"
			}
		],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "newOwner",
				"type": "address"
			}
		],
		"name": "transferOwnership",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"stateMutability": "payable",
		"type": "fallback"
	},
	{
		"stateMutability": "payable",
		"type": "receive"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "owner",
				"type": "address"
			},
			{
				"internalType": "address",
				"name": "spender",
				"type": "address"
			}
		],
		"name": "allowance",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "account",
				"type": "address"
			}
		],
		"name": "balanceOf",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "decimals",
		"outputs": [
			{
				"internalType": "uint8",
				"name": "",
				"type": "uint8"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "DOMAIN_SEPARATOR",
		"outputs": [
			{
				"internalType": "bytes32",
				"name": "",
				"type": "bytes32"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "eip712Domain",
		"outputs": [
			{
				"internalType": "bytes1",
				"name": "fields",
				"type": "bytes1"
			},
			{
				"internalType": "string",
				"name": "name",
				"type": "string"
			},
			{
				"internalType": "string",
				"name": "version",
				"type": "string"
			},
			{
				"internalType": "uint256",
				"name": "chainId",
				"type": "uint256"
			},
			{
				"internalType": "address",
				"name": "verifyingContract",
				"type": "address"
			},
			{
				"internalType": "bytes32",
				"name": "salt",
				"type": "bytes32"
			},
			{
				"internalType": "uint256[]",
				"name": "extensions",
				"type": "uint256[]"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "ETH_USD_FEED_ADDRESS",
		"outputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "account",
				"type": "address"
			}
		],
		"name": "getETHBalance",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "getETHUSDPrice",
		"outputs": [
			{
				"internalType": "int256",
				"name": "",
				"type": "int256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "getTransactions",
		"outputs": [
			{
				"components": [
					{
						"internalType": "address",
						"name": "user",
						"type": "address"
					},
					{
						"internalType": "uint256",
						"name": "amountETH",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "amountECNY",
						"type": "uint256"
					},
					{
						"internalType": "bool",
						"name": "isPurchase",
						"type": "bool"
					},
					{
						"internalType": "bytes32",
						"name": "transactionHash",
						"type": "bytes32"
					}
				],
				"internalType": "struct eCNY.Transaction[]",
				"name": "",
				"type": "tuple[]"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "account",
				"type": "address"
			}
		],
		"name": "getTransactionsForAccount",
		"outputs": [
			{
				"components": [
					{
						"internalType": "address",
						"name": "user",
						"type": "address"
					},
					{
						"internalType": "uint256",
						"name": "amountETH",
						"type": "uint256"
					},
					{
						"internalType": "uint256",
						"name": "amountECNY",
						"type": "uint256"
					},
					{
						"internalType": "bool",
						"name": "isPurchase",
						"type": "bool"
					},
					{
						"internalType": "bytes32",
						"name": "transactionHash",
						"type": "bytes32"
					}
				],
				"internalType": "struct eCNY.Transaction[]",
				"name": "",
				"type": "tuple[]"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "name",
		"outputs": [
			{
				"internalType": "string",
				"name": "",
				"type": "string"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "owner",
				"type": "address"
			}
		],
		"name": "nonces",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "owner",
		"outputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "symbol",
		"outputs": [
			{
				"internalType": "string",
				"name": "",
				"type": "string"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "totalSupply",
		"outputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"name": "transactions",
		"outputs": [
			{
				"internalType": "address",
				"name": "user",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "amountETH",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "amountECNY",
				"type": "uint256"
			},
			{
				"internalType": "bool",
				"name": "isPurchase",
				"type": "bool"
			},
			{
				"internalType": "bytes32",
				"name": "transactionHash",
				"type": "bytes32"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "",
				"type": "uint256"
			}
		],
		"name": "transactionsForAccount",
		"outputs": [
			{
				"internalType": "address",
				"name": "user",
				"type": "address"
			},
			{
				"internalType": "uint256",
				"name": "amountETH",
				"type": "uint256"
			},
			{
				"internalType": "uint256",
				"name": "amountECNY",
				"type": "uint256"
			},
			{
				"internalType": "bool",
				"name": "isPurchase",
				"type": "bool"
			},
			{
				"internalType": "bytes32",
				"name": "transactionHash",
				"type": "bytes32"
			}
		],
		"stateMutability": "view",
		"type": "function"
	}
]
// 使用 Web3 提供者
const provider = new Web3.providers.HttpProvider('https://sepolia.infura.io/v3/acdcdade84a94831b56beabb5b282dad');
const web3 = new Web3(provider);

// eCNY 合约地址
const contractAddress = '0x732c25817590274461C2d89198aD096c323F9F88';
// 创建合约实例
const eCNYContract = new web3.eth.Contract(eCNYABI, contractAddress);

// 更新账户信息的函数
function updateAccount(newWalletAddress, newPrivateKey) {
	// 更新 localStorage
	localStorage.setItem('walletAddress', newWalletAddress);
	localStorage.setItem('privateKey', newPrivateKey);

	// 更新全局变量
	account.address = newWalletAddress;
	account.privateKey = newPrivateKey;

	// 重新初始化 Web3 实例以使用新的私钥
	const newWeb3 = new Web3(new Web3.providers.HttpProvider('https://sepolia.infura.io/v3/acdcdade84a94831b56beabb5b282dad'));
	const neweCNYContract = new newWeb3.eth.Contract(eCNYABI, contractAddress);

	// 显示钱包地址
	document.getElementById('walletAddress').textContent = account.address;

	// 重新加载余额
	loadETHBalance(newWeb3);
	loadBalance(newWeb3, neweCNYContract);
}

// 从 localStorage 获取钱包地址和私钥
const walletAddress = localStorage.getItem('walletAddress'); // 获取存储的钱包地址
const privateKey = localStorage.getItem('privateKey'); // 获取存储的私钥

// 将获取的信息存储在 account 对象中
const account = {
	address: walletAddress,
	privateKey: privateKey
};

// 确保在 DOM 加载完成后执行
document.addEventListener('DOMContentLoaded', function () {
	// 检查钱包地址是否存在
	if (account.address) {
		document.getElementById('walletAddress').textContent = account.address; // 显示钱包地址
		loadBalance(web3, eCNYContract); // 加载 eCNY 余额
		loadETHBalance(web3); // 加载 ETH 余额
	} else {
		document.getElementById('walletAddress').textContent = '未找到钱包地址'; // 若钱包地址不存在，显示错误信息
	}
});

// 加载用户 ETH 余额
async function loadETHBalance() {
	try {
		const balanceWei = await web3.eth.getBalance(walletAddress); // 获取钱包地址的 ETH 余额（单位：Wei）
		const balanceEth = web3.utils.fromWei(balanceWei, 'ether'); // 将 Wei 转换为 ETH
		document.getElementById('ethBalanceDisplay').textContent = '余额: ' + balanceEth + ' ETH'; // 显示 ETH 余额
		console.log('ETH 余额:', balanceEth); // 输出调试信息
	} catch (error) {
		console.error('加载 ETH 余额失败:', error); // 捕获并显示错误信息
		document.getElementById('ethBalanceDisplay').textContent = '加载余额失败: ' + error.message; // 显示加载失败信息
	}
}

// 加载用户 eCNY 代币余额
async function loadBalance() {
	const balance = await eCNYContract.methods.balanceOf(account.address).call(); // 调用智能合约获取 eCNY 余额
	const balanceInEth = web3.utils.fromWei(balance, 'ether'); // 将 Wei 转换为 eCNY
	document.getElementById('balanceDisplay').textContent = '余额: ' + balanceInEth + ' eCNY'; // 显示 eCNY 余额
}

// 购买 eCNY 代币
async function buyTokensWithETH() {
	const amount = document.getElementById('buyAmount').value; // 获取用户输入的购买金额（ETH）
	if (!amount || parseFloat(amount) <= 0) { // 检查金额是否有效
		alert('请输入有效的 ETH 数量'); // 若无效，弹出提示
		return;
	}

	try {
		const data = eCNYContract.methods.buyTokensWithETH().encodeABI(); // 编码调用 buyTokensWithETH 方法
		const tx = {
			from: walletAddress, // 发送者地址
			to: contractAddress, // 合约地址
			value: web3.utils.toWei(amount, 'ether'), // 转换金额到 Wei
			data: data, // 包含方法调用的编码数据
			gas: 3000000, // 设定 gas 上限
			gasPrice: await web3.eth.getGasPrice() // 获取当前 gas 价格
		};

		const signedTx = await web3.eth.accounts.signTransaction(tx, privateKey); // 使用私钥签名交易
		const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction); // 发送已签名的交易

		alert('购买成功！交易哈希: ' + receipt.transactionHash); // 交易成功弹出提示
		loadETHBalance(); // 更新 ETH 余额
		loadBalance(); // 更新 eCNY 余额
		return receipt; // 返回交易回执
	} catch (error) {
		console.error('签名或发送交易失败:', error); // 捕获并显示交易失败原因
		alert('交易失败: ' + (error.message || '未知错误')); // 弹出失败提示
		// 尝试解码交易失败原因
		if (error && error.rawTransaction) {
			try {
				const decoded = web3.eth.abi.decodeLog(error.rawTransaction.logs); // 解码失败原因日志
				alert(`交易失败: ${decoded}`); // 弹出失败原因
			} catch (decodeError) {
				console.error('解码回滚原因失败:', decodeError); // 捕获并显示解码失败信息
			}
		}
		alert('交易失败: ' + (error.message || '未知错误')); // 再次弹出失败提示
		return null; // 返回 null 防止后续代码出错
	}
}

// 处理购买按钮点击事件
document.getElementById('buyButton').addEventListener('click', async function () {
	try {
		const result = await buyTokensWithETH();
		alert('购买成功！交易哈希: ' + result.transactionHash);
		loadBalance(); // 重新加载余额
	} catch (error) {
		console.error('购买失败:', error);
		alert('购买失败: ' + error.message);
	}
});

// 出售代币换取 ETH 的函数
async function sellTokensForETH(amount) {
	const tokenAmount = web3.utils.toWei(amount, 'ether'); // 将输入的数量转换为最小单位（例如 Wei）
	const tx = {
		from: account.address, // 交易发起账户地址
		to: contractAddress, // 目标合约地址
		gas: 2000000, // 设置 gas 限额
		gasPrice: await web3.eth.getGasPrice(), // 获取当前 gas 价格
		data: eCNYContract.methods.sellTokensForETH(tokenAmount).encodeABI() // 编码合约调用的数据
	};

	try {
		// 使用账户私钥签署交易
		const signedTx = await web3.eth.accounts.signTransaction(tx, account.privateKey);
		// 发送签名后的交易
		return await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
	} catch (error) {
		console.error('签名或发送交易失败:', error); // 打印错误日志
		throw new Error('出售失败: ' + (error.message || '未知错误')); // 抛出自定义错误
	}
}

// 处理出售按钮点击事件
document.getElementById('sellButton').addEventListener('click', async function () {
	const amount = document.getElementById('sellAmount').value; // 获取出售代币数量

	if (!amount || parseFloat(amount) <= 0) { // 验证输入是否有效
		alert('请输入有效的代币数量');
		return;
	}

	try {
		// 调用 sellTokensForETH 函数并获取结果
		const result = await sellTokensForETH(amount);
		alert('出售成功！交易哈希: ' + result.transactionHash); // 显示交易哈希
		loadBalance(); // 重新加载余额
	} catch (error) {
		console.error('出售失败:', error); // 打印错误日志
		alert('出售失败: ' + error.message); // 显示错误信息
	}
});

// 加载初始余额
loadBalance();
// eCNY 代币批量转账
document.getElementById('batchTransferButton').addEventListener('click', async function () {
	const recipientsInput = document.getElementById('recipients').value; // 获取接收者地址
	const amountsInput = document.getElementById('amounts').value; // 获取转账金额

	const recipients = recipientsInput.split(',').map(addr => addr.trim()); // 将接收者地址转换为数组
	const amounts = amountsInput.split(',').map(amount => web3.utils.toWei(amount.trim(), 'ether')); // 转换金额为最小单位

	if (recipients.length !== amounts.length) { // 检查地址和金额数量是否匹配
		alert('接收者和金额的数量必须相同');
		return;
	}

	try {
		const tx = {
			from: account.address, // 交易发起账户
			to: contractAddress, // 目标合约地址
			gas: 3000000, // 设置 gas 限额
			gasPrice: await web3.eth.getGasPrice(), // 获取当前 gas 价格
			data: eCNYContract.methods.batchTransferTokens(recipients, amounts).encodeABI() // 编码批量转账数据
		};

		const signedTx = await web3.eth.accounts.signTransaction(tx, account.privateKey); // 签署交易
		const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction); // 发送交易

		alert('批量转账成功！交易哈希: ' + receipt.transactionHash); // 显示成功信息
		loadBalance(); // 重新加载余额
	} catch (error) {
		console.error('批量转账失败:', error); // 打印错误日志
		alert('批量转账失败: ' + error.message); // 显示错误信息
	}
});

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('batchETHTransferButton').addEventListener('click', handleBatchETHTransfer);

    // 监听金额输入框和接收者输入框的变化
    document.getElementById('ethRecipients').addEventListener('input', updateEstimatedGasFee);
    document.getElementById('ethAmounts').addEventListener('input', updateEstimatedGasFee);
});

//批量转账ETH
async function updateEstimatedGasFee() {
    const recipientsInput = document.getElementById('ethRecipients').value; // 获取接收者地址
    const amountsInput = document.getElementById('ethAmounts').value; // 获取转账金额

    const recipients = recipientsInput.split(',').map(addr => addr.trim()); // 将接收者地址转换为数组
    const amounts = amountsInput.split(',').map(amount => web3.utils.toWei(amount.trim(), 'ether')); // 转换金额为最小单位

    if (recipients.length !== amounts.length) { // 检查地址和金额数量是否匹配
        return;
    }

    try {
        const gasPrice = await web3.eth.getGasPrice(); // 获取当前 gas 价格
        const gasPriceBigInt = BigInt(gasPrice); // 将 gasPrice 转换为 BigInt 类型
        let totalGas = 0n; // 使用 BigInt 来累加 gas 费用

        for (let i = 0; i < recipients.length; i++) {
            // 估算每笔交易的 gas 费用
            const tx = {
                from: account.address,
                to: recipients[i],
                value: amounts[i],
                gas: 21000, // 设置 gas 限额
                gasPrice: gasPrice // 获取当前 gas 价格
            };

            const estimatedGas = await web3.eth.estimateGas(tx); // 估算 gas
            totalGas += BigInt(estimatedGas); // 累加所有交易的 gas 费用
        }

        // 更新预计的 Gas 费用到页面
        const estimatedGasFee = web3.utils.fromWei((totalGas * gasPriceBigInt).toString(), 'ether'); // 总 gas 费用
        document.getElementById('estimatedGasFee').textContent = `${estimatedGasFee} ETH`;
    } catch (error) {
        console.error('计算预计 Gas 费用失败:', error); // 打印错误日志
        document.getElementById('estimatedGasFee').textContent = '计算失败';
    }
}

async function handleBatchETHTransfer() {
    const recipientsInput = document.getElementById('ethRecipients').value; // 获取接收者地址
    const amountsInput = document.getElementById('ethAmounts').value; // 获取转账金额

    const recipients = recipientsInput.split(',').map(addr => addr.trim()); // 将接收者地址转换为数组
    const amounts = amountsInput.split(',').map(amount => web3.utils.toWei(amount.trim(), 'ether')); // 转换金额为最小单位

    if (recipients.length !== amounts.length) { // 检查地址和金额数量是否匹配
        alert('接收者和金额的数量必须相同');
        return;
    }

    try {
        const balance = await web3.eth.getBalance(account.address); // 获取账户余额
        let totalAmount = amounts.reduce((sum, amount) => {
            return BigInt(sum) + BigInt(amount); // 累加所有转账金额
        }, BigInt(0));

        // 更新总转账金额到页面
        const totalAmountInEther = web3.utils.fromWei(totalAmount.toString(), 'ether'); // 转换回 ether 显示
        document.getElementById('totalAmount').textContent = `${totalAmountInEther} ETH`;

        // 检查余额是否足够
        if (totalAmount > BigInt(balance)) { // 比较余额和总转账金额
            alert('余额不足，无法完成所有转账');
            return;
        }

        // 估算每笔转账的 gas 费用
        const gasPrice = await web3.eth.getGasPrice(); // 获取当前 gas 价格
        const gasPriceBigInt = BigInt(gasPrice); // 将 gasPrice 转换为 BigInt 类型
        let totalGas = 0n; // 使用 BigInt 来累加 gas 费用

        for (let i = 0; i < recipients.length; i++) {
            // 估算每笔交易的 gas 费用
            const tx = {
                from: account.address,
                to: recipients[i],
                value: amounts[i],
                gas: 21000, // 设置 gas 限额
                gasPrice: gasPrice // 获取当前 gas 价格
            };

            const estimatedGas = await web3.eth.estimateGas(tx); // 估算 gas
            totalGas += BigInt(estimatedGas); // 累加所有交易的 gas 费用
        }

        // 更新预计的 Gas 费用到页面
        const estimatedGasFee = web3.utils.fromWei((totalGas * gasPriceBigInt).toString(), 'ether'); // 总 gas 费用
        document.getElementById('estimatedGasFee').textContent = `${estimatedGasFee} ETH`;

        // 遍历接收者地址并依次转账
        for (let i = 0; i < recipients.length; i++) {
            const tx = {
                from: account.address, // 交易发起账户
                to: recipients[i], // 当前接收者地址
                value: amounts[i], // 转账金额
                gas: 21000, // 设置 gas 限额
                gasPrice: gasPrice // 获取当前 gas 价格
            };

            const signedTx = await web3.eth.accounts.signTransaction(tx, account.privateKey); // 签署交易
            const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction); // 发送交易

            // 显示每笔转账结果
            document.getElementById('transferResult').innerHTML +=
                `转账到 ${recipients[i]} 成功！交易哈希: ${receipt.transactionHash}<br>`;
        }

        alert('所有转账已成功处理！'); // 提示完成所有转账
        loadETHBalance(); // 重新加载余额
    } catch (error) {
        console.error('批量 ETH 转账失败:', error); // 打印错误日志
        alert('批量 ETH 转账失败: ' + error.message); // 显示错误信息
    }
}

async function checkTransactions() {
	try {
		const currentAddress = localStorage.getItem('walletAddress');
		if (!currentAddress) throw new Error('未找到钱包地址');
		if (!web3.utils.isAddress(currentAddress)) throw new Error('当前地址格式不正确');

		const transactionsDisplay = document.getElementById('transactionsDisplay');
		transactionsDisplay.textContent = '正在加载交易明细...';

		const etherscanApiKey = 'KUCTFVBI8H74IZK89CEMETQA8CKZD2KKQG';
		const ethUrl = `https://api-sepolia.etherscan.io/api?module=account&action=txlist&address=${currentAddress}&startblock=0&endblock=99999999&sort=desc&apikey=${etherscanApiKey}`;
		const tokenUrl = `https://api-sepolia.etherscan.io/api?module=account&action=tokentx&address=${currentAddress}&startblock=0&endblock=99999999&sort=desc&apikey=${etherscanApiKey}`;

		const ethResponse = await fetch(ethUrl);
		const tokenResponse = await fetch(tokenUrl);

		if (!ethResponse.ok || !tokenResponse.ok) throw new Error('无法连接到Etherscan API');

		const ethData = await ethResponse.json();
		const tokenData = await tokenResponse.json();

		transactionsDisplay.innerHTML = '';
		const allTransactions = [...ethData.result, ...tokenData.result];
		if (allTransactions.length === 0) {
			transactionsDisplay.textContent = '没有交易明细';
			return;
		}

		allTransactions.forEach(transaction => {
			const transactionElement = document.createElement('div');
			transactionElement.classList.add('transaction-summary');

			let transactionDetails = '';
			let amount = '';
			let tokenSymbol = transaction.tokenSymbol || 'ETH';

			if (transaction.tokenSymbol) {
				// 代币交易
				amount = web3.utils.fromWei(transaction.value, 'ether');
				transactionDetails = `交易哈希: ${transaction.hash}, 数量: ${amount} ${tokenSymbol}, 时间: ${new Date(transaction.timeStamp * 1000).toLocaleDateString()}`;
			} else {
				// ETH 交易
				amount = web3.utils.fromWei(transaction.value, 'ether');
				transactionDetails = `交易哈希: ${transaction.hash}, 数量: ${amount} ETH, 时间: ${new Date(transaction.timeStamp * 1000).toLocaleDateString()}`;
			}

			transactionElement.textContent = transactionDetails;

			// 绑定点击事件以显示详细信息模态框
			transactionElement.addEventListener('click', () => {
				showTransactionModal({
					hash: transaction.hash,
					from: transaction.from,
					to: transaction.to,
					value: amount,
					blockNumber: transaction.blockNumber,
					timeStamp: new Date(transaction.timeStamp * 1000).toLocaleString(),
					gasPrice: transaction.gasPrice ? web3.utils.fromWei(transaction.gasPrice, 'gwei') : 'N/A',
					gasUsed: transaction.gasUsed,
					tokenSymbol: tokenSymbol
				});
			});

			transactionsDisplay.appendChild(transactionElement);
		});
	} catch (error) {
		console.error('获取交易明细失败:', error);
		alert('获取交易明细失败: ' + error.message);
		document.getElementById('transactionsDisplay').textContent = '获取交易明细失败';
	}
}

// 模态框展示详细交易信息
function showTransactionModal(transaction) {
	const modal = document.getElementById('transactionModal');
	const modalContent = document.getElementById('modalContent');

	modalContent.innerHTML = `
		<p>交易哈希: ${transaction.hash}</p>
		<p>发送地址: ${transaction.from}</p>
		<p>接收地址: ${transaction.to}</p>
		<p>转账数量: ${transaction.value} ${transaction.tokenSymbol}</p>
		<p>区块: ${transaction.blockNumber}</p>
		<p>交易时间: ${transaction.timeStamp}</p>
		<p>燃料价格: ${transaction.gasPrice} Gwei</p>
		<p>燃料使用量: ${transaction.gasUsed}</p>
	`;

	modal.style.display = 'block';
}

// 关闭模态框
function closeTransactionModal() {
	document.getElementById('transactionModal').style.display = 'none';
}

// 绑定查看交易明细按钮
document.getElementById('checkTransactionsButton').addEventListener('click', checkTransactions);

// 绑定关闭模态框按钮
document.getElementById('closeModal').addEventListener('click', closeTransactionModal);
